package cn.cj.erp.common.utils.encrypt;

import cn.cj.erp.common.utils.Assert;
import cn.hutool.core.util.StrUtil;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * AES加解密工具
 *
 * @author chenjian
 */
public class AesUtil {
    /**
     * 算法名称
     */
    public static final String KEY_ALGORITHM = "AES";
    /**
     * 加解密算法/模式/填充方式
     */
    public static final String ALGORITHM_AES_ECB_PKCS5 = "AES/ECB/PKCS5Padding";

    /**
     * 加密方法，采用AES_128位
     *
     * @param plainText 待加密数据
     * @param secretKey 秘钥，必须是16的倍数
     * @return String
     */
    public static String encrypt(String plainText, String secretKey) {
        Assert.notEmpty(secretKey, "secret key cannot be empty");
        Assert.notEmpty(secretKey, "plain text cannot be empty");
        Assert.notEmpty(secretKey, "secret key cannot be empty");
        // 判断Key是否为16位
        if (secretKey.length() != 16) {
            throw new IllegalArgumentException("sKey长度需要为16位");
        }

        try {
            byte[] raw = secretKey.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec secretkeySpec = new SecretKeySpec(raw, KEY_ALGORITHM);

            //"算法/模式/补码方式"
            Cipher cipher = Cipher.getInstance(ALGORITHM_AES_ECB_PKCS5);
            cipher.init(Cipher.ENCRYPT_MODE, secretkeySpec);
            byte[] encrypted = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));

            //此处使用BASE64做转码功能，同时能起到2次加密的作用。
            return new Base64().encodeToString(encrypted);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 解密方法 对AES_128位解密
     *
     * @param cipherText 待解密数据
     * @param secretKey  秘钥，必须是16的倍数
     * @return String
     */
    public static String decrypt(String cipherText, String secretKey) {
        try {
            byte[] raw = secretKey.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec secretkeySpec = new SecretKeySpec(raw, KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(ALGORITHM_AES_ECB_PKCS5);

            cipher.init(Cipher.DECRYPT_MODE, secretkeySpec);
            //先用base64解密
            byte[] encrypted1 = new Base64().decode(cipherText);
            byte[] original = cipher.doFinal(encrypted1);
            return new String(original, StandardCharsets.UTF_8);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * 将key补全为16的倍数
     *
     * @param key 需要补全的key
     * @return java.lang.String
     */
    public static String genKey(String key) {
        if (StrUtil.isEmpty(key)) {
            return null;
        }
        if (key.length() % 16 != 0) {
            return StrUtil.padPre(key, key.length() + 16 - key.length() % 16, 'A');
        }
        return key;
    }
}
